<template>
  <div class="login-container">
    <h2>用户登录</h2>
    <form @submit.prevent="submitForm">
      <div class="form-group">
        <label>用户名:</label>
        <input
          type="text"
          v-model="loginName"
          required
          placeholder="请输入用户名"
        >
      </div>
      <div class="form-group">
        <label>密码:</label>
        <input
          type="password"
          v-model="password"
          required
          placeholder="请输入密码"
        >
      </div>
      <button type="submit">{{ isRegistering ? '注册' : '登录' }}</button>
      <p class="toggle-mode" @click="isRegistering = !isRegistering">
        {{ isRegistering ? '已有账号？立即登录' : '没有账号？立即注册' }}
      </p>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from "axios";
import { useRouter } from 'vue-router'; // 添加路由导入

const loginName = ref('');
const password = ref('');
const isRegistering = ref(false); // 新增注册状态标识
const router = useRouter(); // 创建路由实例

const submitForm = async () => {
  try {
    const url = isRegistering.value ? '/user/register' : '/user/login';
    const response = await axios.post(url,
        {
          login_name: loginName.value,
          password: password.value
        },{
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      // body: JSON.stringify({
      //   login_name: loginName.value,
      //   password: password.value
      // })
    });

    console.log(`${isRegistering.value ? '注册' : '登录'}成功:`, response.data);
    alert(`${isRegistering.value ? '注册成功，请登录！' : '登录成功！'}`);
    // 保存用户信息到localStorage
    localStorage.setItem('userInfo', JSON.stringify({
      login_name: loginName.value,
      // 如果后端返回token也可以保存
      token: response.data.token
    }));
    // 注册成功后自动切换回登录状态
    if (isRegistering.value) {
      isRegistering.value = false;
      loginName.value = '';
      password.value = '';
    }
    // 登录成功后跳转到主页
    await router.push('/home');
  } catch (error) {
    console.error('错误:', error);
    // 这里可以添加错误处理逻辑
  }
};
</script>

<style scoped>
/* 新增切换链接样式 */
.toggle-mode {
  margin-top: 1rem;
  color: #007bff;      /* 改为标准蓝色 */
  text-decoration: underline; /* 确保下划线存在 */
  cursor: pointer;
  transition: color 0.3s;
}

.toggle-mode:hover {
  color: #0056b3;     /* 悬停时加深蓝色 */
}

.login-container {
  max-width: 400px;
  margin: 2rem auto;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.form-group {
  margin-bottom: 1rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
}

input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  background-color: #42b983;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>
